<template>
  <div>
    <div class="header-box">
      <div class="lt">
        <!-- 选择证书列表 -->
        <div class="series-box">
          <el-dropdown
            placement="bottom-start"
            @command="changeAc"
            @visible-change="acSearchVal = ''"
          >
            <p class="el-dropdown-link pointer">
              <!-- <strong>/</strong> -->
              <span>{{ accountLabel }}</span>
              <i class="el-icon-caret-bottom"></i>
            </p>
            <el-dropdown-menu slot="dropdown">
              <div class="search-box">
                <el-input
                  v-model="acSearchVal"
                  placeholder="请输入"
                  suffix-icon="el-input__icon el-icon-search"
                  size="small"
                ></el-input>
              </div>
              <el-dropdown-item
                v-for="(item, index) in accountOptions"
                :key="item.uuid"
                :label="item.secretName"
                :value="item.uuid"
                :command="item.uuid"
                :class="acValue === item.uuid ? 'acitve' : ''"
              >
                <span>{{ item.secretName }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <!-- 选择秘钥-->
        <div class="series-box">
          <el-dropdown
            placement="bottom-start"
            @command="changeORG"
            @visible-change="orgSearchVal = ''"
          >
            <p class="el-dropdown-link pointer">
              <strong>/</strong>
              <span>{{ orgLabel }}</span>
              <i class="el-icon-caret-bottom"></i>
            </p>
            <el-dropdown-menu slot="dropdown">
              <div class="search-box">
                <el-input
                  v-model="orgSearchVal"
                  placeholder="请输入"
                  suffix-icon="el-input__icon el-icon-search"
                  size="small"
                ></el-input>
              </div>
              <div class="el-dropdown-menu-scroll">
                <el-dropdown-item
                  v-for="(item, index) in orgOptions"
                  :key="item.orgId"
                  :label="item.orgName"
                  :value="item.orgId * 1"
                  :command="item.orgId"
                  :class="orgValue * 1 === item.orgId * 1 ? 'acitve' : ''"
                >
                  <span>{{ item.orgName }}</span>
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <!-- 选择广告系列 -->
        <div class="series-box">
          <el-dropdown
            placement="bottom-start"
            @command="changeAdSeries"
            @visible-change="seriesSearchVal = ''"
          >
            <p class="el-dropdown-link pointer">
              <strong>/</strong>
              <span>{{ seriesLabel }}</span>
              <i class="el-icon-caret-bottom"></i>
            </p>
            <el-dropdown-menu slot="dropdown">
              <div class="search-box">
                <el-input
                  v-model="seriesSearchVal"
                  placeholder="请输入"
                  suffix-icon="el-input__icon el-icon-search"
                  size="small"
                ></el-input>
              </div>
              <div class="el-dropdown-menu-scroll">
                <el-dropdown-item
                  class=""
                  :class="seriesValue === 'all' ? 'acitve' : ''"
                  command="all"
                >
                  <span>全部广告系列</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-for="(item, index) in seriesOptions"
                  :key="item.campaignId"
                  :label="item.showName"
                  :value="item.campaignId"
                  :command="item.campaignId"
                  :class="seriesValue === item.campaignId * 1 ? 'acitve' : ''"
                >
                  <p class="flex" style="justify-content: flex-start">
                    <i
                      v-if="item.displayStatus === 'DELETED'"
                      class="hui-color status-dot"
                    ></i>
                    <i
                      v-else-if="item.displayStatus === 'RUNNING'"
                      class="liu-color status-dot"
                    ></i>
                    <i v-else class="yellow-color status-dot"></i>
                    <span style="width: 98%" class="overflow-ellipsis">{{
                      item.showName
                    }}</span>
                  </p>
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <!-- 选择广告组 -->
        <div v-if="routerName !== 'typeOverview'" class="group-box flex">
          <el-dropdown
            placement="bottom-start"
            @command="changeAdGroup"
            @visible-change="groupSearchVal = ''"
          >
            <p class="el-dropdown-link pointer">
              <strong>/</strong>
              <span>{{ groupLabel }}</span>
              <i class="el-icon-caret-bottom"></i>
            </p>
            <el-dropdown-menu slot="dropdown">
              <div class="search-box">
                <el-input
                  v-model="groupSearchVal"
                  placeholder="请输入"
                  suffix-icon="el-input__icon el-icon-search"
                  size="small"
                ></el-input>
              </div>
              <div class="el-dropdown-menu-scroll">
                <el-dropdown-item
                  :class="groupValue === 'all' ? 'acitve' : ''"
                  command="all"
                >
                  <span>全部广告组</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-for="(item, index) in groupOptions"
                  :key="item.adGroupId"
                  :label="item.name"
                  :value="item.adGroupId"
                  :command="item.adGroupId * 1"
                  :class="groupValue === item.adGroupId * 1 ? 'acitve' : ''"
                >
                  <p v-if="item.campaignDisplayStatus !== 'ON_HOLD'">
                    <span
                      ><i
                        v-if="item.displaystatus === 'RUNNING'"
                        class="liu-color status-dot"
                      ></i>
                      <i
                        v-else-if="item.displayStatus === 'DELETED'"
                        class="hui-color status-dot"
                      ></i
                      >
                       <i
                        v-else
                        class="yellow-color status-dot"
                      ></i
                      >{{ item.name }}</span
                    >
                  </p>
                  <p v-else>
                    <span><i
                        class="yellow-color status-dot"
                      ></i
                      >{{ item.name }}</span>
                  </p>
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div class="rt">
        <time-zone-box></time-zone-box>
      </div>
    </div>
    <el-dialog
      :title="serialType === 'add' ? '创建广告系列组' : '修改广告系列组'"
      :visible.sync="dialogFormVisible"
      :modal-append-to-body="false"
      width="480px"
    >
      <div v-if="serialType !== 'add'" class="op-info flex">
        <p class="lt webfont-Medium">名称</p>
        <p class="rt">ID：{{ serialForm.id }}</p>
      </div>
      <el-form
        ref="serialform"
        label-width="0px"
        :model="serialForm"
        :rules="rules"
        @submit.native.prevent
      >
        <el-form-item prop="name">
          <el-input
            v-model.trim="serialForm.name"
            :placeholder="serialForm.placeholder"
            size="small"
            @input="serialNameInput"
            @keyup.native.enter="
              () => {
                serialType !== 'add' ? hanldeModifySerial() : hanldeAddSerial();
              }
            "
            @focus="handleFocus"
          ></el-input>
        </el-form-item>
      </el-form>

      <div
        slot="footer"
        class="dialog-footer"
        style="position: relative; z-index: 20000"
      >
        <el-button class="cancel-btn defult" @click="dialogFormVisible = false"
          >取 消</el-button
        >
        <el-button
          v-if="serialType !== 'add'"
          type="success"
          :disabled="btnLoading"
          class="defult"
          @click="hanldeModifySerial"
          >确 定</el-button
        >
        <el-button
          v-else
          type="success"
          :disabled="btnLoading"
          class="defult"
          @click="hanldeAddSerial"
          >创建</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  findAcOrOrgList, // 获取所有秘钥以及下属
  findOrgAll,
  findCampaign, // campaign
  findAdgroupsList, // 查询所有的Ad
  findSerialAll, // 查询所有广告系列组
  addSerial, // 创建所有广告系列组；
  editSerial, // 编辑某个广告系列组；
  removeSerial, // 删除某个广告系列组
} from "@/api/overView";

import { mapActions } from "vuex";
// 时间计时
import timeZoneBox from "@/components/timeZoneBox/index.vue";

export default {
  components: {
    timeZoneBox,
  },
  props: {
    // 广告系列
  },
  data() {
    var validateSerialName = (rule, value, callback) => {
      var regTextChar = /^[\u4e00-\u9fa5A-Za-z0-9\-\_]*$/;
      if (value === "") {
        callback(new Error("请输入广告系列组名称"));
      } else {
        const flag = regTextChar.test(value);
        if (!flag)
          return callback(new Error("只能汉字,字母,数字,下划线,横杠组成"));
        callback();
      }
    };

    return {
      btnLoading: false,
      rules: {
        name: [
          {
            required: true,
            message: "请输入广告系列组名称",
            trigger: "blur",
          },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20个字符",
            trigger: "blur",
          },
          {
            validator: validateSerialName,
            trigger: "blur",
          },
        ],
      },
      serialType: "add",
      serialForm: {
        currencyType: this.$store.state.user.unit,
        name: "",
        id: undefined,
        placeholder: undefined,
        teamId: this.$store.state.team.teamId || "",
      },

      dialogFormVisible: false,
      routerName: undefined,

      acValue: "", // 自助投放为空，协同投放才有值
      orgValue: "", // 自助投放为空，协同投放才有值
      serialValue: "", // 协同投放没有这个值，自助投放才有值
      seriesValue: "all", // 广告系列默认值
      groupValue: "all", // 广告组默认值
      seriesOne: {}, // 当前选中的广告系列
      groupOne: {}, // 当前选中的广告组
      groupSearchVal: "", // 广告组的搜索词
      seriesSearchVal: "", // 广告系列的搜索词
      serialSearchVal: "", // 广告系列组的搜索词
      orgSearchVal: "", // 秘钥的搜索词
      acSearchVal: "", // 证书的搜索词
    };
  },

  computed: {
    roleName() {
      const name = this.$store.state.user.userInfo.roleName;
      if (name === "visitor") {
        return "团队管理员";
      } else if (name === "manager") {
        return "系列组管理员";
      } else if (name === "finance") {
        return "账号财务";
      } else if (name === "readOnly") {
        return "广告只读";
      } else if (name === "advManager") {
        return "广告管理员";
      } else {
        return "团队系列组只读";
      }
    },

    typeValue() {
      if (!this.$route.query.modelType) {
        return "help";
      } else {
        return this.$route.query.modelType;
      }
    },

    helpDis() {
      return !this.$isReadOnly(roleName);
    },

    // 广告系列组的按钮权限
    serialBtnIf() {
      const roleName = this.$store.state.user.userInfo.roleName;
      return roleName === "visitor" || roleName === "admin";
    },
    // 秘钥
    accountOptions() {
      if (this.acSearchVal.length) {
        const arr = this.$store.state.overview.allAc;
        const name = this.acSearchVal.trim().toUpperCase();
        const searchArr = arr.filter((item) => {
          const secretName = item.secretName.toUpperCase();
          return secretName.indexOf(name) > -1;
        });
        return searchArr;
      } else {
        return this.$store.state.overview.allAc;
      }
    },

    // 证书Org
    orgOptions() {
      if (this.orgSearchVal.length) {
        const arr = this.$store.state.overview.allOrg;
        const name = this.orgSearchVal.trim().toUpperCase();
        const searchArr = arr.filter((item) => {
          const orgName = item.orgName.toUpperCase();
          return orgName.indexOf(name) > -1;
        });
        return searchArr;
      } else {
        return this.$store.state.overview.allOrg;
      }
    },

    // 全部广告系列组
    serialOptions() {
      const arr = this.$store.state.overview.allSerial;
      if (this.serialSearchVal.length) {
        const name = this.serialSearchVal.trim().toUpperCase();
        const searchArr = arr.filter((item) => {
          const serialName = item.name.toUpperCase();
          return serialName.indexOf(name) > -1;
        });
        return searchArr;
      } else {
        return arr;
      }
    },

    // 全部广告系列
    seriesOptions() {
      const arr = this.$store.state.overview.allCa;
      if (arr.length) {
        // 名称设置
        const arr1 = arr.map((item) => {
          item.showName = item.name;

          return item;
        });

        // 搜索词
        const val = this.seriesSearchVal.trim().toUpperCase();
        if (this.seriesSearchVal.length) {
          const searchArr = arr1.filter((item) => {
            const seriesName = item.showName.toUpperCase();
            return seriesName.indexOf(val) > -1;
          });
          return searchArr;
        } else {
          return arr1;
        }
      } else {
        return [];
      }
    },

    // 广告组
    groupOptions() {
      const arr = this.$store.state.overview.allAd;
      if (this.groupSearchVal) {
        const val = this.groupSearchVal.trim().toUpperCase();
        const searchArr = this.$store.state.overview.allAd.filter((item) => {
          const groupName = item.name.toUpperCase();
          return groupName.indexOf(val) > -1;
        });
        return searchArr;
      } else {
        return arr;
      }
    },

    // 证书的显示名称
    accountLabel() {
      const accountOptions = this.$store.state.overview.allAc;
      const index = accountOptions.findIndex((item) => {
        return item.uuid === this.acValue;
      });
      if (index === -1) {
        return "暂无数据";
      } else {
        return accountOptions[index].secretName;
      }
    },
    // 秘钥的显示名称
    orgLabel() {
      const arr = this.$store.state.overview.allOrg;
      const index = arr.findIndex((item) => {
        return item.orgId * 1 === this.$route.query.orgId * 1;
      });

      if (index === -1) {
        return "暂无数据";
      }
      return arr[index].orgName;
    },

    // 广告系列组显示名称
    serialLabel() {
      const serialOptions = this.$store.state.overview.allSerial;
      const index = serialOptions.findIndex((item) => {
        return item.id * 1 === this.serialValue;
      });
      if (index > -1) {
        return serialOptions[index].name;
      } else {
        const roleName = this.$store.state.user.userInfo.roleName;
        if (roleName === "visitor" || roleName === "admin") {
          return "请先创建广告系列组";
        } else {
          return "暂无数据";
        }
      }
    },

    // 广告系列显示名称
    seriesLabel() {
      // console.log(this.seriesValue, '你好,这个是判断广告系列选择器')
      if (this.seriesValue === "all") {
        return "全部广告系列";
      } else {
        const arr = this.$store.state.overview.allCa;
        const item = arr.find((item) => {
          return item.campaignId * 1 === this.seriesValue;
        });
        const label = item.name;
        return label;
      }
    },

    // 广告组名称
    groupLabel() {
      if (this.groupValue === "all") {
        return "全部广告组";
      } else {
        const arr = this.$store.state.overview.allAd;
        const item = arr.find((item) => {
          return item.adGroupId * 1 === this.groupValue;
        });
        return item.name;
      }
    },
  },

  watch: {
    $route: {
      async handler(newval, oldval) {
        // 投放模式改变
        this.routerName = this.$route.name;
        if (
          this.$route.query.modelType === "help" ||
          !this.$route.query.modelType
        ) {
          // 如果是协同投放

          this.acValue = this.$route.query.uuid || "";
          this.orgValue = this.$route.query.orgId * 1 || "";

          if (!this.$route.query.uuid && !this.$route.query.orgId) {
            // 如果只是切换投放类型 没有制定证书和秘钥;
            await this.findAllAccount();
            /* console.log(this.accountOptions) */
            return this.$router.replace({
              name: "typeOverview",
              query: {
                modelType: "help",
                uuid:
                  this.accountOptions.length > 0
                    ? this.accountOptions[0].uuid
                    : "",
                aId:
                  this.accountOptions.length > 0
                    ? this.accountOptions[0].aid
                    : "",
                orgId:
                  this.accountOptions.length > 0
                    ? this.accountOptions[0].org[0].orgId
                    : "",
              },
            });
          }

          if (
            !oldval ||
            !oldval.query ||
            oldval.query.uuid !== newval.query.uuid
          ) {
            await this.findAllAccount();
          }

          if (
            !oldval ||
            !oldval.query ||
            oldval.query.orgId !== newval.query.orgId
          ) {
            this.acValue = this.$route.query.uuid;
            await this.findAllOrg();
          }

          if (this.$route.query.uuid && this.$route.query.orgId) {
            this.acValue = this.$route.query.uuid;
            this.orgValue = this.$route.query.orgId * 1;

            this.handleRouteChange();
            return false;
          }
          return false;
        }
      },
      // 深度观察监听
      deep: true,
      immediate: true,
    },

    "$store.state.user.unit": function (newval, oldval) {
      this.$router.replace({
        name: "typeOverview",
        query: {},
      });
      (this.acValue = ""), // 自助投放为空，协同投放才有值
        (this.orgValue = ""), // 自助投放为空，协同投放才有值
        (this.seriesValue = "all");
      this.findCampaign();
    },
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    handleFocus() {
      if (this.serialType !== "add" && !this.serialForm.name) {
        this.serialForm.name = this.serialForm.placeholder;
      }
    },
    handleRouteChange() {
      // console.log('进来了没')
      // 下面是判断在哪个页面了；
      if (this.routerName === "typeOverview") {
        // 如果是数据概览页面   查询广告系列
        this.findCampaign();
        this.seriesValue = "all";
        return;
      } else if (this.routerName === "seriesOverview") {
        // 如果是广告系列详情页面
        // 查询广告系列是否存在
        const index = this.$store.state.overview.allCa.findIndex((item) => {
          const campaignId =
            this.$route.query.campaignId || this.$route.query.campaignid;
          return item.campaignId * 1 === campaignId * 1;
        });

        // 如果不存在则跳回数据概览页面
        if (index === -1) {
          this.$router.replace({
            name: "typeOverview",
            query: {
              modelType: this.$route.query.modelType || "",
              newTime: new Date().getTime(),
            },
          });
          return;
        } else {
          this.seriesValue =
            this.$route.query.campaignId * 1 ||
            this.$route.query.campaignid * 1;
          this.groupValue = "all";
          // 如果存在则查询广告组
          return this.findAdgroupsList();
        }
      } else if (this.routerName === "groupOverview") {
        this.seriesValue = this.$route.query.campaignId * 1;
        this.groupValue = this.$route.query.adGroupId * 1;
        // 如果是广告组详情页面
        const index = this.$store.state.overview.allAd.findIndex((item) => {
          const adGroupId =
            this.$route.query.adGroupId || this.$route.query.adGroupid;
          return item.adGroupId * 1 === adGroupId * 1;
        });
        if (index === -1) {
          this.$router.replace({
            name: "typeOverview",
            query: {
              modelType: this.$route.query.modelType || "",
              campaignId:
                this.$route.query.campaignId || this.$route.query.campaignid,
            },
          });
          return;
        } else {
          this.groupValue =
            this.$route.query.adGroupId * 1 || this.$route.query.adGroupid * 1;
          return;
        }
      }
    },

    // 搜索所有的证书信息
    findAllAccount() {
      this.$message.closeAll();
      const obj = {
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || "",
      };

      return new Promise((resolve, reject) => {
        findAcOrOrgList(obj).then((res) => {
          const data = res.data.data;
          this.$store.commit("overview/SET_ALLAC", data);
          if (data.length > 0) {
            resolve(data);
          } else {
            // 如果没有上传证书
            this.$message.closeAll();
            const pushFlag =
              this.$store.state.user.userInfo.roleName === "visitor" ||
              this.$store.state.user.userInfo.roleName === "admin";
            const msgInfo = pushFlag
              ? `<p class="flex" style="width:320px">
                            <span>请先上传证书</span>
                            <em class="pointer">去绑定</em>
                          </p>`
              : `<p class="flex" style="width:320px">
                          <span>请先上传证书</span>
                        </p>`;

            const message = this.$message({
              type: "error",
              dangerouslyUseHTMLString: true,
              message: msgInfo,
            });
            // this.$router.replace({
            //   name: 'typeOverview'
            // })
            if (pushFlag) {
              message.$el.querySelector("em").onclick = () => {
                this.$message.closeAll();
                this.$router.push("/user/zs_bind");
              };
              return;
            }
            resolve(data);
          }
        });
      });
    },

    // 搜索所有的证书Id
    findAllOrg() {
      return new Promise((resolve, reject) => {
        const index = this.accountOptions.findIndex((item) => {
          return item.uuid === this.acValue;
        });
        if (index === -1) return false;

        // 如果这个私钥已经失效了 则给出提示
        if (this.accountOptions[index].roleName === "invalid_client") {
          this.$message.closeAll();
          let msgInfo = `<p class="flex" style="width:320px">
         <span>当前秘钥已失效,请重新绑定</span>
       `;
          if (
            this.$store.state.user.userInfo.roleName === "visitor" ||
            this.$store.state.user.userInfo.roleName === "admin"
          ) {
            msgInfo += `<em class="pointer">去绑定</em>`;
          }
          msgInfo += "</p>";
          const message = this.$message({
            type: "error",
            dangerouslyUseHTMLString: true,
            message: msgInfo,
          });
          if (
            this.$store.state.user.userInfo.roleName === "visitor" ||
            this.$store.state.user.userInfo.roleName === "admin"
          ) {
            message.$el.querySelector("em").onclick = () => {
              this.$message.closeAll();
              this.$router.push("/user/zs_bind");
            };
          }
        }
        const aId = this.accountOptions[index].aid;
        findOrgAll({
          aId,
          currencyType: this.$store.state.user.unit,
          teamId: this.$store.state.team.teamId || "",
        }).then((res) => {
          const data = res.data.data;
          this.$store.commit("overview/SET_ALLORG", data);
          resolve(data || []);

          if (data.length && data) {
            const index1 = this.orgOptions.findIndex((item) => {
              return item.orgId * 1 === this.$route.query.orgId * 1;
            });
            if (index1 === -1) {
              this.$router.replace({
                name: "typeOverview",
                query: {
                  modelType: "help",
                  uuid: this.accountOptions[0].uuid,
                  orgId: this.orgOptions[0].orgId,
                },
              });
              return;
            } else {
              this.orgValue = this.$route.query.orgId * 1;
            }
          } else {
            this.$store.commit("overview/SET_ALLCA", []);
          }
        });
      });
    },

    // 查询全部广告系列组
    findAllSerial() {
      return new Promise(async (resolve, reject) => {
        const obj = {
          currencyType: this.$store.state.user.unit,
          teamId: this.$store.state.team.teamId || "",
        };
        try {
          const res = await this.$store.dispatch("overview/getAllSerial", obj);
          /* console.log(res, '广告系列组数据') */
          if (res.data.code === 20000 && res.data.data.length) {
            const index = res.data.data.findIndex((item) => {
              return item.id * 1 === this.serialValue * 1;
            });
            if (index > -1) {
              resolve(res.data);
            } else {
              this.$router.replace({
                name: this.$route.name,
                query: {
                  modelType: "help",
                  serialId: res.data.data[0].id,
                },
              });
              return reject(res);
            }
          } else {
            // 如果没有广告系列组
            this.serialValue = "";
            this.$store.commit("overview/SET_ALLCA", []);
            this.$router.replace({
              name: this.$route.name,
              query: {
                modelType: "help",
                serialId: "1",
              },
            });
            return reject(res);
          }
        } catch (err) {
          return reject(err);
        }

        // findSerialAll(obj).then(res => {
        //   if (res.data.code === 20000) {
        //     resolve(res)
        //   } else {
        //     reject()
        //   }
        // }).catch(err => {
        //   return reject(err)
        // })
      });
    },

    // 搜索所有的Campaign数据
    async findCampaign() {
      const obj = {
        orgId: this.orgValue, // 自助投放为空
        uuid: this.acValue,
        aId: this.$route.query.aId || this.$route.query.aid || "",
        appid: "", // 当前需求 写死 为空
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || "",
        campaignGroupId: this.serialValue,
      };
      const res = await this.$store.dispatch("overview/getAllCampaign", obj);
      if (res.data.code === 20000) {
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍候重试");
      }
    },

    // 搜索所有的Adgroup数据
    async findAdgroupsList() {
      const obj = {
        campaignId: this.$route.query.campaignId,
        orgId: this.orgValue, // 自助投放为空
        uuid: this.acValue,
        aId: this.$route.query.aId || this.$route.query.aid || "",
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || "",
      };
      const res = await this.$store.dispatch("overview/getAllAdgroup", obj);
      if (res.data.code === 20000) {
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍候重试");
      }
    },

    // 选择证书
    changeAc(val) {
      if (val === this.acValue && this.$route.name === "typeOverview")
        return false;
      const indexObj = this.$store.state.overview.allAc.find((item) => {
        return item.uuid === val;
      });
      const obj = {
        uuid: val,
        orgId: indexObj.org[0].orgId * 1,
        aId: indexObj.aid,
        modelType: this.typeValue,
      };
      this.$router.push({
        name: "typeOverview",
        query: { ...obj, newTime: new Date().getTime() },
      });
    },

    // 选择秘钥
    changeORG(val) {
      /* console.log(this.orgOptions) */
      if (val === this.orgValue && this.$route.name === "typeOverview")
        return false;
      const obj = {
        orgId: val,
        uuid: this.acValue,
        aId: this.$route.query.aId || this.$route.query.aid || "",
        modelType: this.typeValue,
        newTime: new Date().getTime(),
      };
      this.$emit("typeChange", obj);
    },
    // 切换广告系列组
    changeSerial(val) {
      // 如果当前值等于选择值且在
      if (val === this.serialValue && this.$route.name === "typeOverview")
        return false;
      const obj = {
        serialId: val,
        modelType: "",
      };
      this.$router.replace({
        name: "typeOverview",
        query: { ...obj, newTime: new Date().getTime() },
      });
    },

    // 选择广告系列
    changeAdSeries(val) {
      // 如果当前选择的是全部广告系列，之前也是全部广告系列则不做任何操作
      if (val === "all" && this.seriesValue === "all") return false;
      // 如果当前值等于选择值，且没有选择广告组,且在广告系列详情页面；则不做任何操作；
      if (
        this.seriesValue * 1 === val * 1 &&
        this.groupValue === "all" &&
        this.$route.name === "seriesOverview"
      ) {
        return false;
      }

      this.seriesValue = val;
      this.groupValue = "all";
      let obj = {};
      if (val !== "all") {
        const index = this.seriesOptions.findIndex((item) => {
          return item.campaignId * 1 === this.seriesValue;
        });
        obj = {
          modelType: "help",
          campaignId: val,
          caStatus: this.seriesOptions[index].displayStatus,
          orgId: this.orgValue,
          uuid: this.acValue,
          aId: this.$route.query.aId || this.$route.query.aid || "",
        };

        this.seriesOne = this.seriesOptions[index];
      } else {
        obj = {
          campaignId: "all",
          modelType: this.$route.query.modelType || "help",
          orgId: this.orgValue,
          uuid: this.acValue,
          aId: this.$route.query.aId || this.$route.query.aid || "",
        };
        this.seriesOne = {};
      }

      this.$emit("seriesChange", obj);
    },

    // 选择广告组
    changeAdGroup(val) {
      // 如果当前选择的是全部广告组，之前也是全部广告组则不做任何操作
      if (val === "all" && this.groupValue === "all") return false;
      // 如果当前值等于选择值，且没有选择广告组；则不做任何操作；
      if (this.groupValue * 1 === val * 1) return false;
      this.groupValue = val;
      let obj = {};
      if (val !== "all") {
        const index = this.groupOptions.findIndex((item) => {
          return item.adGroupId * 1 === val;
        });
        this.groupOne = this.groupOptions[index];

        obj = {
          ...this.$route.query,
          adchannelType: this.seriesOne.adchannelType,
          adGroupId: this.groupOne.adGroupId,
          adStatus: this.groupOne.displayStatus,
          orgId: this.orgValue,
          uuid: this.acValue,
          aId: this.$route.query.aId || this.$route.query.aid || "",
        };
        this.$emit("adChange", obj);
      } else {
        this.changeAdSeries(this.seriesValue);
      }
    },

    // 点击了编辑广告系列组按钮，点击了新增广告系列组按钮
    editSerialOrAddSerial(data) {
      this.btnLoading = false;

      if (data === "add") {
        this.serialType = "add";
        this.serialForm.name = "";
        this.serialForm.id = undefined;
        this.serialForm.placeholder = "请输入广告系列组名称";
      } else {
        this.serialType = "edit";
        this.serialForm.name = "";
        this.serialForm.placeholder = data.name;
        this.serialForm.id = data.id;
      }
      if (this.$refs.serialSelect) {
        this.$refs.serialSelect.blur();
      }

      if (this.$refs.addDown) {
        this.$refs.addDown.hide();
      }

      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.serialform.resetFields();
      });
    },

    // 点击了删除广告系列组按钮
    delSerial(item) {
      this.$confirm(
        "一旦移除便无法恢复或修改，历史记录报告仍可查看，冻结金额可能需5-10工作日后解冻",
        "警告!移除广告系列组属于永久性操作",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonClass: "defult",
          cancelButtonClass: "defult",
        }
      )
        .then(async () => {
          try {
            const obj = {
              id: item.id,
              name: item.name,
              teamId: this.$store.state.team.teamId || "",
              currencyType: this.$store.state.user.unit,
            };

            const res = await removeSerial(obj);
            if (res.data.code === 20000) {
              this.$message.closeAll();
              this.$message({
                duration: 1500,
                message: res.data.message || "删除成功",
                type: "success",
              });

              if (this.serialValue * 1 === item.id) {
                return this.changeSerial("");
              }

              this.findAllSerial();
              this.serialForm.name = "";
              this.dialogFormVisible = false;
            } else {
              this.$message.closeAll();
              this.$message({
                duration: 1500,
                message: res.data.message || "删除失败",
                type: "error",
              });
            }
          } catch (err) {}
        })
        .catch(() => {});
    },

    async hanldeModifySerial() {
      this.$refs["serialform"].validate(async (valid) => {
        this.btnLoading = true;
        if (valid) {
          if (
            this.serialForm.name == "" ||
            this.serialForm.name === this.serialForm.placeholder
          ) {
            return (this.dialogFormVisible = false);
          } else {
            const { name, id } = this.serialForm;
            const teamId = this.$store.state.team.teamId || "";
            const currencyType = this.$store.state.user.unit;
            try {
              const res = await editSerial({
                name,
                id,
                teamId,
                currencyType,
              });
              this.btnLoading = false;
              if (res.data.code === 20000) {
                this.$message.closeAll();
                this.$message({
                  duration: 1500,
                  message: res.data.message || "修改成功",
                  type: "success",
                });
                this.findAllSerial();
                this.serialForm.name = "";
                this.dialogFormVisible = false;
              } else {
                this.btnLoading = false;
                this.$message.closeAll();
                this.$message({
                  duration: 1500,
                  message: res.data.message || "创建失败",
                  type: "error",
                });
              }
            } catch (e) {
              this.btnLoading = false;
            }
          }
        } else {
          this.btnLoading = false;
        }
      });
    },
    hanldeAddSerial() {
      this.$refs["serialform"].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true;
          const obj = JSON.parse(JSON.stringify(this.serialForm));
          const res = await addSerial({
            ...obj,
            teamId: this.$store.state.team.teamId || "",
            currencyType: this.$store.state.user.unit,
          });
          this.btnLoading = false;
          if (res.data.code === 20000) {
            this.$message.closeAll();
            this.$message({
              duration: 1500,
              message: res.data.message || "创建成功",
              type: "success",
            });
            this.findAllSerial();
            this.serialForm.name = "";
            this.dialogFormVisible = false;
            this.$forceUpdate();
          } else {
            this.$message.closeAll();
            this.$message({
              duration: 1500,
              message: res.data.message || "创建失败",
              type: "error",
            });
          }
        } else {
          this.btnLoading = false;
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped="true">
@import "../../../../../styles/variables.scss";

.header-box {
  margin-left: 10px;
  background-color: #f9f9f9;
  position: relative;
  z-index: 4;
}

.search-box {
  padding: 0;
  margin-bottom: 12px;

  /deep/ input::-webkit-input-placeholder {
    /*Webkit browsers*/
    color: #acb6c2;
    font-size: 14px;
  }

  /deep/ input:-moz-placeholder {
    /*Mozilla Firefox 4 to 8*/
    color: #acb6c2;
    font-size: 14px;
  }

  /deep/input::moz-placeholder {
    /*Mozilla Firefox 19+*/
    color: #acb6c2;
    font-size: 14px;
  }

  /deep/ input:-ms-input-placeholder {
    /*Internet Explorer 10+*/
    color: #acb6c2;
    font-size: 14px;
  }
}

.el-dropdown-menu-scroll {
  height: auto;
  max-height: 260px;
  overflow: hidden;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 4px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 3px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
    background: #c1c1c1;
    opacity: 0.5;
  }
}

.header-box .series-box .el-select,
.header-box .group-box .el-select,
.header-box .serial-box .el-select {
  max-width: 180px;
  font-size: 14px;

  span {
  }

  ::v-deep .el-input__inner {
    text-align: center;
    padding-left: 8px;
    padding-right: 25px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-clamp: 1;
  }
}

.header-box .type-box .el-dropdown .el-dropdown-link,
.header-box .series-box .el-dropdown .el-dropdown-link,
.header-box .group-box .el-dropdown .el-dropdown-link,
.header-box .serial-box .el-dropdown .el-dropdown-link {
  display: flex;
  align-items: center;
  justify-content: flex-start;

  span {
    max-width: 180px;
    font-size: 14px;
    padding: 0 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-clamp: 1;
    color: $mainColor1;
    font-family: PingFangSC, sans-serif;
  }

  i {
    margin-right: 8px;
    color: rgba(0, 0, 0, 0.5);
  }
}

.el-dropdown-menu.el-popper {
  padding: 10px 12px;
  box-shadow: none;

  .el-dropdown-menu__item.acitve {
    background-color: #f7f7f9;

    p,
    span {
      color: $mainColor1 !important;
    }
  }

  .el-dropdown-menu__item {
    margin-bottom: 12px;
    padding: 10px 12px;
    min-width: 176px;
    max-width: 250px;
    line-height: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-clamp: 1;
    border-radius: 2px;
    i {
      margin-right: 8px;
    }
    &:last-of-type {
      margin-bottom: 0;
    }
  }

  .el-dropdown-menu__item:hover {
    background-color: #f7f7f9;

    p,
    span {
      color: $mainTextColor2;
    }
  }
}

.series-img {
  width: 20px;
  height: 20px;
  overflow: hidden;
  border-radius: 4px;
  margin-right: 8px;
}

.header-box ::v-deep .lt > div {
  .el-select,
  .el-input,
  .el-input__inner {
    border: none !important;
    width: auto;
    background: transparent !important;

    width: 100%;
  }

  .el-select input,
  .el-input input {
    color: $mainColor1;
  }

  .el-input__suffix .el-icon-arrow-up {
    color: rgba(0, 0, 0, 0.5);

    &::before {
      content: "\e78f";
    }
  }
}

.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: nowrap;

  .lt {
    flex: 2;
    justify-content: flex-start;
  }

  .rt {
    flex: 1;
    justify-content: flex-end;
  }

  .lt,
  .rt {
    display: flex;
    align-items: center;

    ::v-deep.item {
      cursor: pointer;

      span {
        font-size: 14px;
        color: $mainColor1;
      }

      .el-icon-caret-bottom {
        font-size: 14px;
        color: $mainTextColor2;
      }
    }

    ::v-deep strong {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #000;
      opacity: 0.6;
    }
  }
}

.status-box {
  span {
    display: inline-block;
    height: 10px;
    width: 10px;
    overflow: hidden;
    border-radius: 50%;
    background-color: red;
    margin-right: 8px;
  }
}

/*  .serial-box {
    border: 1px solid red;

  } */

.serial-op-box {
  width: 336px;
  max-width: 336px;
  min-width: 336px;
  padding: 8px 12px;
  border: none;
  border-radius: 2px;

  &.active {
    background: #f7f7f9;

    .op-header span {
      color: $mainColor1 !important;
    }
  }

  i {
    display: inline-block;
    margin-left: 10px;
    font-size: 16px;
    color: #acb6c2;
    opacity: 0;
    transition: opacity 0.8s;
  }

  &:hover {
    i {
      opacity: 1;
    }
  }

  &:nth-of-type(101) {
    border: none;
    margin-bottom: -5px !important;
  }

  .op-header {
    font-size: 14px;
    line-height: 14px;
  }

  .op-id {
    padding-top: 4px;
    font-size: 12px;
    line-height: 12px;
    color: #acb6c2 !important;
  }
}

.add-serial {
  padding: 12px;
  justify-content: center;
  border-top: 1px solid rgba(57, 68, 78, 0.1);
}

.op-info {
  padding-bottom: 12px;
  font-size: 14px;
  line-height: 14px;

  .lt {
  }

  .rt {
    color: rgba(51, 64, 74, 0.8);
  }
}

.add-serial-box {
  margin-top: 12px;
  border-top: 1px solid #e0e2e7;
  padding: 16px 12px;
  padding-bottom: 8px;

  .icon-add {
    font-size: 16px;
    color: $mainColor1;
    margin-right: 12px;
  }

  em {
    font-size: 16px;
    line-height: 16px;
    font-weight: 400;
  }
}
</style>
